<?php

namespace app\model;

use think\helper\Str;
use think\Model;
use think\model\relation\HasMany;

class Merchant extends Model
{
    public function merSer(): HasMany
    {
        return $this->hasMany(MerchantService::class, 'mid');
    }
    public function insertData(): array
    {
        $data = request()->post();
        if (empty($data['id'])) {
            $data['code'] = $this->code();
            $data['appid'] = $this->appid();
        }
        $this->exists(!empty($data['id']))->save($data);
        return $this->toArray();
    }

    public function pageData(): array
    {
        $param = request()->param();
        $data = $this->where("is_del", 1)->when(!empty($param['name']), function ($query) use ($param) {
            $query->where("name", "like", "%{$param['name']}%");
        })->order('create_time', 'desc')->paginate(['list_rows' => 30, 'page' => $param['page'] ?? 1])->toArray();
        return pageData($data);
    }

    public function updateBalance(): array
    {
        $param = request()->post();
        $data = $this->where('id', $param['id'])->where('state', 1)->where('is_del', 1)->find();
        if (empty($data)) throw new \Exception('商户不存在');
        $this->startTrans();
        if ($param['tag'] == 1) {
            $balance = bcadd($data['balance'], $param['balance'], 2);
        } else {
            $balance = bcsub($data['balance'], $param['balance'], 2);
        }
        $data->save(['balance' => $balance]);
        $user = request()->account ?? [];
        app(MerchantBalanceNotice::class)->save([
            'mid' => $data['id'],
            'admin' => $user['name'] ?? '',
            'tag' => $param['tag'],
            'amount' => $param['amount'],
            'money' => $param['balance'],
            'remark' => $param['remark'] ?? '',
            'order_sn' => date("YmdHis") . Str::random(8, 1),
            'type' => $param['type'],
            'total' => $balance
        ]);
        $this->commit();
        return $data->toArray();
    }

    protected function code(): string
    {
        $code = Str::random(32, 6);
        $count = $this->where('code', $code)->count();
        if ($count > 0) return $this->code();
        return $code;
    }

    protected function appid(): string
    {
        $appid = Str::random(16, 1);
        $count = $this->where('appid', $appid)->count();
        if ($count > 0) return $this->appid();
        return $appid;
    }

    public function search(): array
    {
        return $this->where('is_del', 1)->where('state', 1)->column('id,name');
    }
}
